<template>
  <div>
    <el-dialog
      v-toggle-full
      v-loading.lock="loading"
      class="base-dialog order-input"
      :custom-class="'panna-dialog_medium'"
      :append-to-body="true"
      title="确认入库"
      align="center"
      :close-on-click-modal="false"
      :visible.sync="innerDialogFormVisible"
      @closed="closeDialog"
    >
      <el-table
        :data="tableData"
        :header-cell-style="{ height: '50px' }"
        :cell-style="{ height: '44px', overflow: 'auto' }"
        style="width: 100%; height: auto; overflow: auto"
      >
        <el-table-column align="center" label="物料编号">
          <template slot-scope="scope">
            {{ scope.row.productNum }}
          </template>
        </el-table-column>
        <el-table-column label="物料名称">
          <template slot-scope="scope">
            {{ scope.row.productName }}
          </template>
        </el-table-column>
        <el-table-column label="型号规格">
          <template slot-scope="scope">
            {{ scope.row.size }}
          </template>
        </el-table-column>
        <el-table-column label="单位">
          <template slot-scope="scope">
            {{ scope.row.packingUnit }}
          </template>
        </el-table-column>
        <el-table-column label="待收数量">
          <template slot-scope="scope">
            {{ scope.row.pendingCount }}
          </template>
        </el-table-column>
      </el-table>

      <el-form
        ref="formData"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        style="padding-top: 20px; padding-left: 30px"
        status-icon
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="入库库区"
              :label-width="formLabelWidth"
              prop="storageAreaId"
              :error="errorMsg.storageAreaId"
            >
              <el-select
                ref="selectStorageArea"
                v-model="formData.storageAreaId"
                :multiple="false"
                filterable
                placeholder="请选择库区"
                value-key="id"
                @change="(val) => selectStorageArea(val)"
              >
                <el-option
                  v-for="item in storageAreaOptions"
                  :key="item.id"
                  :label="item.areaName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="入库数量"
              :label-width="formLabelWidth"
              prop="productCount"
              :error="errorMsg.productCount"
            >
              <el-input
                v-model="formData.productCount"
                autocomplete="off"
                type="number"
                min="0"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="证书编号"
              :label-width="formLabelWidth"
              prop="certificateNum"
              :error="errorMsg.certificateNum"
            >
              <el-input
                v-model="formData.certificateNum"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="气瓶编号"
              :label-width="formLabelWidth"
              prop="certificateNum"
              :error="errorMsg.airBottleId"
            >
              <div>
                <div>
                  <el-select v-model="formData.sysBusinessAirBottleId">
                    <el-option
                      v-for="item in airBottleList"
                      :key="item.id"
                      :label="item.num"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <div
                style="display: flex; flex-direction: row; margin-left: -100px"
              >
                <div>
                  <el-button
                    type="primary"
                    icon="el-icon-plus"
                    @click="onNew"
                  ></el-button>
                </div>
                <div style="margin-left: 20px">
                  <el-button
                    type="primary"
                    icon="el-icon-close"
                    @click="onClear"
                  ></el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="生产日期"
              :label-width="formLabelWidth"
              prop="dateManufacture"
            >
              <el-date-picker
                v-model="formData.dateManufacture"
                type="date"
                placeholder="选择检验日期"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备注" :label-width="formLabelWidth">
              <el-input v-model="formData.remark" type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm('formData')">确 认</el-button>
      </div>
      <el-dialog
        v-if="dialogAirBottleVisible"
        class="base-dialog"
        :custom-class="'panna-dialog_medium'"
        title="新增气瓶"
        :visible.sync="dialogAirBottleVisible"
        :append-to-body="true"
        :before-close="handleClose"
      >
        <p slot="title">新增气瓶</p>
        <el-form
          ref="airBottleFormData"
          :model="airBottleFormData"
          class="base-pipeline-layout"
          label-width="130px"
          :rules="airBottleFormDataRules"
          status-icon
        >
          <el-form-item label="气瓶编号" prop="num" style="width: 100%">
            <el-input v-model="airBottleFormData.num"></el-input>
          </el-form-item>
          <el-form-item label="气瓶备注" prop="remark" style="width: 100%">
            <el-input v-model="airBottleFormData.remark"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="base-dialog-footer">
          <el-button :disabled="!submitLoad" type="primary" @click="submitForm"
            >保 存</el-button
          >
          <el-button @click="handleClose">取 消</el-button>
        </span>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { getStorageAreaList } from "../../../../api/Material/Common.js";
import { handle } from "../../../../api/Material/MaterialOrderIn.js";
import { getListNoPage, create } from "../../../../api/AirBottle/AirBottle";
import _ from "lodash";
export default {
  name: "RKInputProductDetailsDialog",
  props: {
    dialogInputDetailsVisible: {
      type: Boolean,
      default: false,
    },
    rowData: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      title: "确认入库",
      loading: false,
      innerDialogFormVisible: false,
      dialogAirBottleVisible: false,
      tableData: [],
      storageAreaOptions: [],
      airBottleList: [],
      submitLoad: true,
      airBottleFormData: {
        num: 0,
        reamrk: "",
      },
      airBottleFormDataRules: {
        num: [
          { required: true, message: "气瓶编号必须填写!", trigger: "blur" },
        ],
      },
      initData: {
        handleId: 0,
        orderId: 0,
        productId: 0,
        productNum: "",
        productName: "",
        productCount: 0,
        storageAreaId: null,
        storageAreaName: null,
        certificateNum: null,
        supplierId: null,
        supplierName: null,
        dateManufacture: null,
        remark: "",
      },
      formData: {
        handleId: 0,
        orderId: 0,
        productId: 0,
        productNum: "",
        productName: "",
        productCount: 0,
        storageAreaId: null,
        storageAreaName: null,
        certificateNum: null,
        supplierId: null,
        supplierName: null,
        dateManufacture: null,
        remark: "",
        sysBusinessAirBottleId: "",
      },
      formRules: {
        storageAreaId: [
          {
            required: true,
            trigger: "change",
            validator: this.Helper.validateFunction,
          },
        ],
        productCount: [
          {
            required: true,
            trigger: "blur",
            validator: this.validateCount,
          },
        ],
      },
      initErrorMsg: {
        supplierId: "",
        productCount: "",
        sysBusinessAirBottleId: "",
      },
      errorMsg: {
        supplierId: "",
        productCount: "",
        sysBusinessAirBottleId: "",
      },
    };
  },
  watch: {},
  created() {
    this.innerDialogFormVisible = this.dialogInputDetailsVisible;
    this.tableData.push(this.rowData);
    this.getListNoPage();
    this.init();
  },
  methods: {
    async init() {
      this.formData = this.rowData;
      await this.getStorageAreaOptions();
    },
    onNew() {
      this.airBottleFormData.num = "";
      this.airBottleFormData.reamrk = "";
      this.dialogAirBottleVisible = true;
    },
    onClear() {
      this.formData.sysBusinessAirBottleId = "";
    },
    // 保存
    submitForm: _.throttle(function() {
      this.$refs["formData"].validate((valid) => {
        debugger;
        if (this.submitLoad) {
          this.submitLoad = false;
          if (valid) {
            create(this.airBottleFormData)
              .then((res) => {
                debugger
                this.getListNoPage();
                this.formData.sysBusinessAirBottleId = res.data;
                this.handleClose();
              })
              .catch((res) => {
                this.submitLoad = true;
              });
          } else {
            this.submitLoad = true;
          }
        }
      });
    }, 2000),

    // 关闭弹框
    handleClose() {
      this.dialogAirBottleVisible = false;
      this.submitLoad = true;
    },
    getListNoPage() {
      getListNoPage({ status: 10 })
        .then((res) => {
          this.airBottleList = res.data;
        })
        .catch((res) => {
          this.airBottleList = [];
        });
    },
    getStorageAreaOptions() {
      return new Promise((resolve) => {
        getStorageAreaList({ StorageId: this.formData.storageId }).then(
          (res) => {
            this.storageAreaOptions = res.data.dataList;
            resolve();
          }
        );
      });
    },

    selectStorageArea(val) {
      var obj = {};
      obj = this.storageAreaOptions.find(function(i) {
        return i.id === val;
      });
      this.formData.storageAreaId = obj.id;
      this.formData.storageAreaName = obj.areaName;
    },
    cancel() {
      this.innerDialogFormVisible = false;
      this.$emit("update:dialogInputDetailsVisible", false);
      this.$emit("confirmAfter");
      this.$refs["formData"].resetFields();
    },
    closeDialog() {
      this.cancel();
    },
    confirm() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          const pendingCount = parseInt(this.rowData.pendingCount);
          const productCount = parseInt(this.formData.productCount);
          if (productCount === 0) {
            this.$message.error("入库数量不能为0");
            return false;
          }
          if (productCount > pendingCount) {
            this.$message.error("入库数量不能大于待收数量");
            return false;
          }
          this.loading = true;
          handle(this.formData)
            .then((res) => {
              if (res.code === 200) {
                this.closeDialog();
              } else {
                this.showValidateMsgCheck(res);
              }
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("qualifiedCount", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("unqualifiedCount", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("supplierId", this.errorMsg, res.msg);
      }
    },
    validateCount(rule, value, callback) {
      var pattern = /^\d+$/; // 非负整数
      if (!pattern.test(value)) {
        callback(new Error("数据格式错误"));
      } else {
        callback();
      }
    },
  },
};
</script>

<style lang="scss">
.order-input {
  margin-top: 10px;
  width: 100%;

  .el-dialog__footer .el-button {
    width: 90px;
  }

  .el-table .cell {
    overflow: visible;
  }

  .el-form {
    .el-row {
      height: 60px;

      &:last-child {
        border-bottom: none;
      }

      .el-col {
        &:nth-child(2n + 1) {
          .el-form-item {
            .el-form-item__label {
              border-left: none;
            }
          }
        }

        .el-form-item {
          margin: 0;
          height: 40px;
          line-height: 40px;

          .el-form-item__label {
            height: 100%;
            line-height: 40px;
            text-align: center;
            font-weight: bold;
          }

          .el-form-item__content {
            text-align: left;
            height: 100%;
            line-height: 40px;
            margin-left: 20px;
          }
        }
      }
    }
  }
}
</style>
